﻿using System;
using System.Collections.Generic;
using System.Linq;
using UnityGameFramework.Runtime;
using static TowerDefence_Zombie.PlayerSkillData;

namespace TowerDefence_Zombie.Data
{
    public sealed partial class DataPlayer
    {
        private PlayerDataTemplate _playerData;

        #region 炮塔建造器相关

        public int GetBuilderLevel()
        {
            return _playerData.CurBuilderLevel;
        }

        public int UpBuilderLevel()
        {
            var dataTower = GameEntry.Data.GetData<DataTower>();
            var curBuilderLevel = _playerData.CurBuilderLevel;
            if (dataTower.CheckTowerBuildIsMaxLevel(curBuilderLevel) == false)
            {
                var nextBuilderLevel = curBuilderLevel + 1;
                _playerData.CurBuilderLevel = nextBuilderLevel;
                if (GameEntry.Data.GetData<DataTower>().GetTowerBuildData(nextBuilderLevel, out var buildData))
                {
                    GameEntry.Event.Fire(this, UpgradeTowerBuilderEventArgs.Create(nextBuilderLevel
                        , buildData.BuildItemNum[0]));
                }
                return nextBuilderLevel;
            }
            return curBuilderLevel;
        }

        public int GetBuildSpecialMaterials()
        {
            return (int)GetCurrency(108);
        }

        public bool CheckCanBuyTower()
        {
            if (GameEntry.Data.GetData<DataTower>().GetTowerBuildData(_playerData.CurBuilderLevel, out var buildData))
            {
                return CheckCurrencyIsMeet(buildData.BuildItems, buildData.BuildItemNum);
            }
            return false;
        }

        public bool BuyTower(out int towerId, out int towerLevel)
        {
            towerLevel = towerId = -1;
            var dtDataTower = GameEntry.Data.GetData<DataTower>();
            var dtDataLevel = GameEntry.Data.GetData<DataLevel>();
            if (dtDataTower.GetTowerBuildData(_playerData.CurBuilderLevel, out var buildData)
               && dtDataLevel.GetLevelData(_playerData.CurLevelIndex, out var levelData))
            {
                int currentWeight = 0, totalWeight = 0;
                int weightCount = levelData.TowerWeights.Length;
                for (int i = 0; i < weightCount; i++)
                {
                    totalWeight += levelData.TowerWeights[i];
                }
                int randomValue = UnityEngine.Random.Range(0, totalWeight);
                int randomIndex = 0;
                for (int i = 0; i < weightCount; i++)
                {
                    currentWeight += levelData.TowerWeights[i];
                    if (randomValue < currentWeight)
                    {
                        randomIndex = i;
                        break;
                    }
                }

                towerId = levelData.AllowTowers[randomIndex];
                towerLevel = buildData.BuildTowerLevel;
                RemoveCurrency(buildData.BuildItems, buildData.BuildItemNum, Data.CurrencyEvent.BuyTower);

                GameEntry.Event.Fire(this, BuildTowerEventArgs.Create(towerId, towerLevel));
                return true;
            }
            return false;
        }

        #endregion

        #region 炮塔位置建造器
        public int GetTowerPositionLevel()
        {
            return _playerData.TowerPositionLevel;
        }

        public int UpTowerPositionLevel()
        {
            _playerData.TowerPositionLevel++;
            return _playerData.TowerPositionLevel;
        }

        public int GetTowerPositionMaterials()
        {
            return (int)GetCurrency(109);
        }
        #endregion

        #region 炮塔相关

        //机枪手
        public int GetStarSoldierLevel()
        {
            return GetTowerStar(107);
        }

        public int GetStarSoldierTowerMaterials()
        {
            return (int)_playerData.MoneyTypeDataDic[107];
        }

        //冰人
        public int GetIceLevel()
        {
            return GetTowerStar(108);
        }

        public int GetIceTowerMaterials()
        {
            return (int)_playerData.MoneyTypeDataDic[104];
        }

        //老白
        public int GetOldManLevel()
        {
            return GetTowerStar(109);
        }

        public int GetOldManTowerMaterials()
        {
            return (int)_playerData.MoneyTypeDataDic[105];
        }

        //钢铁侠
        public int GetIronManLevel()
        {
            return GetTowerStar(110);
        }

        public int GetIronManTowerMaterials()
        {
            return (int)_playerData.MoneyTypeDataDic[106];
        }

        public int GetTowerStar(int towerId)
        {
            if (!_playerData.TowerStarDic.TryGetValue(towerId, out var star))
            {
                star = 1;
                _playerData.TowerStarDic.Add(towerId, star);
            }
            return star;
        }

        public int UpgradeTowerStar(int towerId)
        {
            int star = GetTowerStar(towerId);
            var dataTower = GameEntry.Data.GetData<DataTower>();
            if (dataTower.GetTowerData(towerId, out var towerData))
            {
                if (star < towerData.GetMaxStar())
                {
                    star += 1;
                    _playerData.TowerStarDic[towerId] = star;
                    GameEntry.Event.Fire(this, UpgradeTowerStarEventArgs.Create(towerId, star));

                    Dictionary<string, string> dic = new()
                    {
                        { "ID", towerId.ToString() },
                        { "level", star.ToString() },
                    };
                    UPTrace.UPTraceApi.traceDictionary("T0_levelup", dic);
                }
            }
            return star;
        }

        #endregion

        #region 关卡

        public int GetCurBattleLevel()
        {
            return _playerData.CurLevelIndex;
        }

        public bool IsMaxLevel()
        {
            return GameEntry.Data.GetData<DataLevel>().IsMaxLevel(_playerData.CurLevelIndex);
        }

        public bool NextLevel(out int nextLevel, out LevelData nextLevelData)
        {
            if (IsMaxLevel())
            {
                nextLevel = _playerData.CurLevelIndex;
                GameEntry.Data.GetData<DataLevel>().GetLevelData(nextLevel, out nextLevelData);
                return false;
            }
            var curLevel = _playerData.CurLevelIndex;
            _playerData.CurLevelIndex = curLevel + 1;
            nextLevel = _playerData.CurLevelIndex;
            GameEntry.Data.GetData<DataLevel>().GetLevelData(nextLevel, out nextLevelData);

            int unlockSynthesisNum = nextLevelData.UnlockSynthesis.Length;
            if (unlockSynthesisNum > 0)
            {
                var dataSynthesis = GameEntry.Data.GetData<DataSynthesis>();
                for (int i = 0; i < unlockSynthesisNum; i++)
                {
                    int synthesisId = nextLevelData.UnlockSynthesis[i];
                    if (synthesisId > 0)
                    {
                        if (dataSynthesis.GetSynthesisGridData(synthesisId, out _))
                        {
                            dataSynthesis.UnlockSynthesisGridArea(synthesisId);
                        }
                    }
                }
            }
            return true;
        }

        public bool RollbackLevel(out int backLevel, out LevelData levelData)
        {
            if (_playerData.CurLevelIndex <= 1)
            {
                backLevel = _playerData.CurLevelIndex = 1;
                GameEntry.Data.GetData<DataLevel>().GetLevelData(backLevel, out levelData);
                return false;
            }
            _playerData.CurLevelIndex -= 1;
            backLevel = _playerData.CurLevelIndex;
            GameEntry.Data.GetData<DataLevel>().GetLevelData(backLevel, out levelData);
            return true;
        }

        /// <summary>
        /// 标记最近的Boss关卡挑战结果
        /// </summary>
        /// <param name="result"></param>
        public void SignBossLevelChallengeResult(bool result)
        {
            _playerData.BossLevelChallengeResult = result;
        }

        /// <summary>
        /// 过去最近的Boss关卡挑战结果
        /// </summary>
        /// <returns></returns>
        public bool GetBossLevelChallengeResult()
        {
            return _playerData.BossLevelChallengeResult;
        }

        /// <summary>
        /// 添加宝箱获取过的关卡
        /// </summary>
        /// <param name="level"></param>
        public void AddTreasureGainLevel(int level)
        {
            _playerData.TreasureGainedLevel.Add(level);
        }

        /// <summary>
        /// 判断关卡是否已获取过宝箱
        /// </summary>
        /// <param name="level"></param>
        /// <returns></returns>
        public bool GetLevelIsGainedTreasure(int level)
        {
            return _playerData.TreasureGainedLevel.Contains(level);
        }

        #endregion

        public void GetBoxAward(List<MoneyInfo> moneyInfos, CurrencyEvent currencyEvent)
        {
            for (int i = 0; i < moneyInfos.Count; i++)
            {
                AddCurrency(moneyInfos[i].MoneyId, moneyInfos[i].Count, currencyEvent);
            }
        }

        private void InitPlayerData()
        {
            _playerData.OnlineTime = 1;
            _playerData.CurLevelIndex = 1;
            _playerData.BossLevelChallengeResult = true;
            _playerData.TreasureGainedLevel = new();
            _playerData.CurBuilderLevel = 1;
            _playerData.MoneyTypeDataDic = new();
            _playerData.TowerStarDic = new();
            _playerData.SignDate = new();
            _playerData.SignTask.Add(DateTime.Now.ToString());
            _playerData.PlayerTaskData = new PlayerDailyTaskData();
            _playerData.PlayerSkillData = new PlayerSkillData();
            _playerData.CarSkillData = new CarSkillData();


            MoneyEntityData[] moneyEntityData = GameEntry.Data.GetData<MoneyEntity>().GetAllMoneyEntityData();
            for (int i = 0; i < moneyEntityData.Length; i++)
            {
                var moneyItem = moneyEntityData[i];
                GetCurrency(moneyItem.Id, moneyItem.InitNum);
            }

            var dtTower = GameEntry.DataTable.GetDataTable<DRTower>();
            var drTowerArray = dtTower.GetAllDataRows();
            for (int i = 0; i < drTowerArray.Length; i++)
            {
                _playerData.TowerStarDic.Add(drTowerArray[i].Id, 1);
            }
        }

        public int GetOnlineTime()
        {
            return _playerData.OnlineTime;
        }

        //签到
        public int GetSiginCount()
        {
            return _playerData.SignDate.Count;
        }

        public bool CheckIsCanSigin()
        {
            if (_playerData.SignDate.Count == 0)
                return true;
            else if (_playerData.SignDate.Count >= 7)
                return false;
            else
            {
                //判断今天是否签到
                DateTime lastDate = DateTime.Parse(_playerData.SignDate[^1]);
                return !IsSameDay(lastDate, DateTime.Now);
            }
        }
        public void SetSigin()
        {
            _playerData.SignDate.Add(DateTime.Now.ToString());
        }

        private bool IsSameDay(DateTime date1, DateTime date2)
        {
            return date1.Year == date2.Year &&
                   date1.Month == date2.Month &&
                   date1.Day == date2.Day;
        }

        public PlayerDataTemplate GetPlayerData()
        {
            return _playerData;
        }
    }
}